package me.zhengjie.modules.system.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.google.common.base.Joiner;
import me.zhengjie.modules.system.domain.ExamInfo;
import me.zhengjie.modules.system.domain.vo.ExamInfoVo;
import me.zhengjie.modules.system.service.ExamInfoService;
import me.zhengjie.modules.system.service.ExamTypeService;
import me.zhengjie.modules.system.service.dto.ExamTypeDto;
import me.zhengjie.modules.system.service.dto.ExamTypeQueryCriteria;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author CN-xianchengzhao
 * @description: TODO
 * @date 2021/11/21 12:14
 */
@Component
public class UploadExamInfoListener implements ReadListener<ExamInfoVo> {

    public static ThreadLocal<Long> atmrLocal = new ThreadLocal<>();

    @Autowired
    ExamInfoService examInfoService;

    @Autowired
    ExamTypeService examTypeService;

    @Override
    public void invoke(ExamInfoVo examInfoVo, AnalysisContext analysisContext) {
        if (StringUtils.isBlank(examInfoVo.getExam())) {
            return;
        }
        ExamTypeQueryCriteria queryCriteria = new ExamTypeQueryCriteria();
        queryCriteria.setTypeName(examInfoVo.getExamType());
        List<ExamTypeDto> list = examTypeService.queryAll(queryCriteria);

        ExamInfo examInfo = new ExamInfo();
        BeanUtils.copyProperties(examInfoVo, examInfo);
        examInfo.setStatus("0");
        examInfo.setAnswer(examInfoVo.getChose());
        String score = examInfo.getScore();
        if (!CollectionUtils.isEmpty(list)) {
            examInfo.setExamTypeId(list.get(0).getId() + "");
        }
        if (StringUtils.isNotBlank(score)) {
            String[] split = score.split(",");
            examInfo.setScore(Joiner.on(";").join(split));
            examInfo.setAnswer(score);
        } else if("1".equals(examInfo.getExamTypeId())){
            examInfo.setScore("1;2");
        }

        if (StringUtils.isNotEmpty(examInfo.getExamNo())) {
            examInfo.setGroupCode(examInfo.getExamNo().substring(0, 4));
        }
        examInfo.setExamDatabaseId(atmrLocal.get());
        examInfoService.create(examInfo);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

}
